package com.zhuhjay.chat.server.handler;

import com.zhuhjay.chat.message.GroupCreateRequestMessage;
import com.zhuhjay.chat.message.GroupCreateResponseMessage;
import com.zhuhjay.chat.server.session.Group;
import com.zhuhjay.chat.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;

/**
 * @author ZhuHJay
 * @date 2023/3/8 22:16
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends AbstractRequestMessageHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        // 创建一个群聊session，将用户添加进去
        Group group = GroupSessionFactory.getGroupSession().createGroup(msg.getGroupName(), msg.getMembers());
        if (group != null) {
            // 群聊存在
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "创建失败, 群聊[" + msg.getGroupName() + "]已存在"));
        } else {
            // 群聊创建成功, 获取所有在线成员进行发送信息
            List<Channel> channels = GroupSessionFactory.getGroupSession().getMembersChannel(msg.getGroupName());
            channels.forEach(channel -> channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已加入[" + msg.getGroupName() + "]群聊")));
        }
    }
}
